#!/usr/bin/env bash
# Summary: List all available phpenv commands
# Usage: phpenv commands [--sh|--no-sh]
#
# List names of all phpenv commands, including 3rd-party ones found in the
# PATH or in phpenv plugins. With `--sh`, list only shell commands.
#
# This functionality is mainly meant for scripting. To see usage help for
# phpenv, run `phpenv help`.

set -e
[ -n "$PHPENV_DEBUG" ] && set -x

# Provide phpenv completions
if [ "$1" = "--complete" ]; then
  echo --sh
  echo --no-sh
  exit
fi

exclude_shell=
command_prefix="phpenv-"

if [ "$1" = "--sh" ]; then
  command_prefix="phpenv-sh-"
  shift
elif [ "$1" = "--no-sh" ]; then
  exclude_shell=1
  shift
fi

shopt -s nullglob

{
  PATH_remain="$PATH"
  # traverse PATH to find "phpenv-" prefixed commands
  while true; do
    path="${PATH_remain%%:*}"
    if [ -n "$path" ]; then
      for phpenv_command in "${path}/${command_prefix}"*; do
        phpenv_command="${phpenv_command##*phpenv-}"
        if [[ -z $exclude_shell || $phpenv_command != sh-* ]]; then
          echo "${phpenv_command##sh-}"
        fi
      done
    fi
    [[ $PATH_remain == *:* ]] || break
    PATH_remain="${PATH_remain#*:}"
  done
} | sort | uniq
